package com.lyh.hkcloud.base;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import com.lyh.hkcloud.R;
import com.lyh.hkcloud.constants.*;
import com.lyh.hkcloud.module.common.ModuleService;
import com.lyh.hkcloud.plugins.zxing.activity.*;
import com.lyh.hkcloud.service.*;
import com.lyh.hkcloud.base.*;
import com.lyh.hkcloud.util.base.*;
import com.lyh.hkcloud.util.http.listener.json.JsonFailuredListener;
import com.lyh.hkcloud.util.http.listener.json.JsonSuccessListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

public abstract class ModuleActivity<P extends com.lyh.hkcloud.base.BaseEntityViewAdapter> extends com.lyh.hkcloud.base.BaseActivity {

    protected TextView tvNowDate;

    protected EditText tvCode;

    private ModuleService service;

    private UserService userService;

    private ImageView ivClose;

    private LinearLayout llClose;

    private TextView tvSum;
    private TextView tvEnter;


    //确认用户ID
    private boolean enabledEnterUser = false;
    protected Integer enterUserId;
    protected String enterPsnCode;
    protected String enterPsnName;
    private String enterTitle;
    private String enterMsg;
    private OnEnterUserListener enterUserListener;


    private TextView tvLast;

    protected CheckBox cbAll;

    protected boolean isLoad = false;

    //数量字段名称
    private String amountFieldName;
    //数量名
    private String amountName;

    protected String codeFieldName = "objnr";


    protected P adapter = (P) new DefaultEntityViewAdapter(getActivity(), new ArrayList<Map<String, Object>>(), enableManualSelection());

    //查询时返回的数据
    protected JSONObject response;
    protected List<Map<String, Object>> list = new ArrayList<>();


    /**
     * 是否启用手动选择框，
     *
     * @return
     */
    protected boolean enableManualSelection() {
        return false;
    }

    /**
     * 二次确认时条码的字段名
     *
     * @return
     */
    protected String getCodeFieldName() {
        return codeFieldName;
    }

    /**
     * 是否启用必选
     *
     * @return
     */
    protected boolean enableRequiredSelect() {
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options_child_menu, menu);
        menu.findItem(R.id.action_person).setTitle(UserInfo.psnCode);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_person:
                //showInfo();
                break;
            case R.id.action_logout:
                logout();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 生成二次验证字段
     *
     * @param list
     * @param fields
     */
    protected void genVerifyField(List<Map<String, Object>> list, String... fields) {
        codeFieldName = "customize_row_key";
        if (list == null || list.isEmpty()) {
            return;
        }

        for (Map<String, Object> map : list) {
            StringBuilder sb = new StringBuilder();
            for (String field : fields) {
                if ("-".equals(field) || "_".equals(field)) {
                    sb.append(field);
                    continue;
                }
                sb.append(MapUtil.getString(map, field));
            }
            map.put(codeFieldName, sb.toString());
        }
    }

    @Override
    protected void init() {
        this.setEnableSubmitConfirm(true);
        initModuleView();
        super.init();
        initModule();
        initActionBar();
    }

    private void initModule() {
        onModuleBeginInit();

        initModuleEvent();
        intModuleData();

        if (enabledEnterUser) {
            showEnterUserDialog();
        }
    }

    @Override
    protected void onClear(View... ignores) {
        isLoad = false;
        super.onClear(ignores);
        ToastUtils.makeText(getActivity(), "", ToastUtils.LENGTH_SHORT).cancel();
        if (list != null) {
            list.clear();
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
        if (cbAll != null) {
            cbAll.setChecked(false);
        }
        intModuleData();
        response = JsonUtil.getBlankJSONObject();
        refreshCount();
        initLoadFocusView();
    }

    /**
     * 显示确认用户框，
     *
     * @param title
     * @param msg
     * @return
     */
    protected void showEnterUser(String title, String msg) {
        showEnterUser(title, msg, null);
    }

    /**
     * 显示确认用户框
     *
     * @param title
     * @param msg
     * @param enterUserListener
     */
    protected void showEnterUser(String title, String msg, OnEnterUserListener enterUserListener) {
        this.enabledEnterUser = true;
        this.enterTitle = title;
        this.enterMsg = msg;
        this.enterUserListener = enterUserListener;
    }

    /**
     * 是否启用提交时提示数量确认框，
     *
     * @param amountName      数量名称,
     * @param amountFieldName 数量字段名称，
     */
    protected void enableAmountSubmitConfirm(String amountName, String amountFieldName) {
        this.enableSubmitConfirm = true;
        this.amountName = amountName;
        this.amountFieldName = amountFieldName;
    }


    private void onModuleBeginInit() {
        service = new ModuleService(getActivity());
        userService = new UserService(getActivity());
    }

    private void initModuleView() {
        if (getNowDateResId() > -1) {
            tvNowDate = findViewById(getNowDateResId());
        }
//        ivClose = findViewById(R.id.iv_close);
//        llClose = findViewById(R.id.ll_close);
//        tvSum = findViewById(R.id.tv_sum);
//        tvEnter = findViewById(R.id.tv_enter);
//        tvLast = findViewById(R.id.tv_last);
//        cbAll = findViewById(R.id.cb_all);
//        tvCode = findViewById(R.id.tv_code);
    }

    protected void changeSort(String objnr) {
        changeSort(objnr, true);
    }

    protected void changeSort(String objnr, boolean autoSubmit) {
        Iterator<Map<String, Object>> iterator = list.iterator();

        Map<String, Object> map = null;
        while (iterator.hasNext()) {
            map = iterator.next();
            if (objnr.equals(map.get(getCodeFieldName()))) {
                list.remove(map);
                break;
            }
            map = null;
        }
        if (map != null) {
            map.put("checked", "1");
            list.add(0, map);
            checkAll();
            adapter.notifyDataSetChanged();

            if (autoSubmit) {
                int enter = 0;
                iterator = list.iterator();
                while (iterator.hasNext()) {
                    if ("1".equals(iterator.next().get("checked"))) {
                        enter++;
                    }
                }
                if (enter > 0 && enter == list.size()) {
                    submit();
                }
            }
        } else {
            ToastUtils.makeText(this, "无效的订单行", ToastUtils.LENGTH_SHORT).show();
        }
    }

    protected List<Map<String, Object>> getItemByKeyValue(List<Map<String, Object>> list, String key, String value) {
        Iterator<Map<String, Object>> iterator = list.iterator();
        List<Map<String, Object>> result = new ArrayList<>();
        while (iterator.hasNext()) {
            Map<String, Object> map = iterator.next();
            if (value.equals(map.get(key))) {
                result.add(map);
            }
        }
        return result;
    }

    protected boolean checkRepeat(String key, String msg, Map<String, Object> data) {
        List<Map<String, Object>> datas = new ArrayList<>();
        datas.add(data);
        return checkRepeat(key, msg, datas);
    }

    protected boolean checkRepeat(String key, String msg, List<Map<String, Object>> datas) {
        for (Map<String, Object> data : datas) {
            for (Map<String, Object> root : list) {
                if (MapUtil.getString(data, key).equals(MapUtil.getString(root, key))) {
                    ToastUtils.makeText(getActivity(), StringUtils.isNotEmpty(msg) ? msg : "重复的条码", ToastUtils.LENGTH_SHORT).show();
                    return false;
                }
            }
        }
        return true;
    }

    protected boolean checkExistAinAllB(String keya, String keyb, String msg, List<Map<String, Object>> datasa, List<Map<String, Object>> datasb) {
        for (Map<String, Object> data : datasa) {
            boolean isExist = false;
            for (Map<String, Object> root : datasb) {
                if (Objects.equals(StringUtils.clearLeftZero(MapUtil.getString(data, keya)), StringUtils.clearLeftZero(MapUtil.getString(root, keyb)))) {
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                ToastUtils.makeText(getActivity(), StringUtils.isNotEmpty(msg) ? msg : "不完全存在的数据", ToastUtils.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    private void showEnterUserDialog() {
        View view = getActivity().getLayoutInflater().inflate(
                R.layout.dialog_enter_user, null);

        view.findViewById(R.id.et_account).requestFocus();
        final EditText etAccount = view.findViewById(R.id.et_account);
        final EditText etPassword = view.findViewById(R.id.et_password);
        TextView tvMsg = view.findViewById(R.id.tv_msg);

        final AlertDialog dialog = new AlertDialog.Builder(getActivity()).
                setIcon(R.drawable.verification).
                setView(view).setTitle(enterTitle).setCancelable(false).create();
        dialog.show();
        view.findViewById(R.id.tv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        getActivity().finish();
                    }
                }, 0);
            }
        });
        tvMsg.setText(enterMsg);

        final Button btnEnter = view.findViewById(R.id.btn_enter);
        btnEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitEnterUser(dialog, etAccount, etPassword, btnEnter);
            }
        });

        etPassword.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    submitEnterUser(dialog, etAccount, etPassword, btnEnter);
                }
                return false;
            }
        });
    }

    private void submitEnterUser(final AlertDialog dialog, final EditText etAccount, final EditText etPassword, final Button btnEnter) {
        if (TextUtils.isEmpty(etAccount.getText())) {
            etAccount.setError("请输入用户名");
            return;
        }
        if (TextUtils.isEmpty(etPassword.getText())) {
            etPassword.setError("请输入密码");
            return;
        }
        btnEnter.setEnabled(false);
        btnEnter.setText("请稍后……");
        userService.verification(etAccount.getText().toString(), etPassword.getText().toString(), new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                btnEnter.setText("确定");
                btnEnter.setEnabled(true);
                JSONArray tenants = response.optJSONArray("tenants");
                int length = tenants.length();
                boolean exists = false;
                for (int i = 0; i < length; i++) {
                    if (tenants.optJSONObject(i).optInt("tenantId") == UserInfo.tenantId.intValue()) {
                        exists = true;
                        break;
                    }
                }
                if (!exists) {
                    etAccount.setError("非法租户用户！");
                    return;
                }
                JSONObject userInfo = response.optJSONObject("userInfo");
                enterUserId = userInfo.optInt("userId");
                enterPsnName = userInfo.optString("userName");
                enterPsnCode = userInfo.optString("account");
                if (enterUserId == null || enterUserId == 0) {
                    etAccount.setError("获取用户信息出错！");
                    return;
                }
                if (enterUserListener != null) {
                    enterUserListener.onEnter(response, new OnEnterUserCallBack() {

                        @Override
                        public void onSuccess() {
                            dialog.dismiss();
                        }

                        @Override
                        public void onFail(String msg) {
                            if (StringUtils.isNotEmpty(msg)) {
                                etAccount.setError(msg);
                            }
                        }
                    });
                } else {
                    dialog.dismiss();
                }
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error",response.optString("message"));
                btnEnter.setText("确定");
                btnEnter.setEnabled(true);
                etAccount.setError(msg);
            }
        });
    }

    protected void refreshCount() {
        if (tvSum == null || tvEnter == null || tvLast == null) {
            return;
        }
        int sum = list.size();
        tvSum.setText(StringUtils.toString(sum, "0"));
        int enter = 0;
        for (Map<String, Object> map : list) {
            if ("1".equals(map.get("checked"))) {
                enter++;
            }
        }
        tvSum.setText(StringUtils.toString(sum, "0"));
        tvEnter.setText(StringUtils.toString(enter, "0"));
        tvLast.setText(StringUtils.toString((sum - enter), "0"));
    }

    /**
     * 检查全选
     */
    protected void checkAll() {
        boolean checkAll = true;
        for (Map<String, Object> map : list) {
            if (!"1".equals(map.get("checked"))) {
                checkAll = false;
                break;
            }
        }
        cbAll.setChecked(checkAll);
        refreshCount();
    }

    protected JSONArray getSelectArray() {
        JSONArray array = new JSONArray();
        for (Map<String, Object> map : list) {
            if ("1".equals(map.get("checked"))) {
                array.put(JsonUtil.toJSONObject(map));
            }
        }
        return array;
    }

    protected List<Map<String, Object>> getSelectList() {
        List<Map<String, Object>> ll = new ArrayList<>();
        for (Map<String, Object> map : list) {
            if ("1".equals(map.get("checked"))) {
                ll.add(map);
            }
        }
        return ll;
    }


    @Override
    protected boolean onValidate() {
        if (adapter == null) {
            ToastUtils.makeText(getActivity(), "请确认是否存在数据。", ToastUtils.LENGTH_SHORT).show();
            return false;
        }
        Map<String, Boolean> verifys = adapter.verifys;
        for (String s : verifys.keySet()) {
            if (!verifys.get(s)) {
                ToastUtils.makeText(getActivity(), "请检查数据项是否填写正确。", ToastUtils.LENGTH_SHORT).show();
                return false;
            }
        }
        if (tvNowDate != null) {
            if (TextUtils.isEmpty(tvNowDate.getText().toString())) {
                ToastUtils.makeText(getActivity(), "过账日期未加载，请返回重试。", ToastUtils.LENGTH_SHORT).show();
                return false;
            }
        }
        /*EditText wmsTools = findViewById(R.id.tv_wmsTools);
        if (wmsTools != null && StringUtils.isEmpty(wmsTools.getText().toString().trim())) {
            ToastUtils.makeText(getActivity(), "请输入箱子号。", ToastUtils.LENGTH_SHORT).show();
            wmsTools.requestFocus();
            return false;
        }*/
        if (enableRequiredSelect()) {
            int count = 0;
            for (Map<String, Object> map : list) {
                if ("1".equals(MapUtil.getString(map, "checked"))) {
                    count++;
                }
            }
            if (count == 0) {
                ToastUtils.makeText(getActivity(), "请选择要过账的数据。", ToastUtils.LENGTH_SHORT).show();
                return false;
            }

            int sumCount = 0;
            float sumAmount = 0;
            if (StringUtils.isNotEmpty(amountFieldName)) {

                for (Map<String, Object> map : list) {
                    if ("1".equals(MapUtil.getString(map, "checked"))) {
                        sumCount++;
                        sumAmount += MapUtil.getFloat(map, amountFieldName, 0);
                    }
                }
                if (sumCount == 0) {
                    LoadingUtils.getInstance(getActivity()).hide();
                    ToastUtils.makeText(getActivity(), "请选择要过账的数据。", ToastUtils.LENGTH_SHORT).show();
                    return false;
                }
                submitConfirmMsg = "本次过账共<big><b><font color=\"red\">" + sumCount + "</font></b></big>条数据，累计" + amountName + "<big><b><font color=\"#008000\">" + sumAmount + "</font></b></big>，确定过账吗？";
            }
        }


        return true;
    }

    /**
     * 全选操作，
     */
    public void selectAll() {
        changeAll(true);
    }

    public void changeAll(boolean checked) {
        if (adapter == null || adapter.getCount() == 0) {
            return;
        }
        if (cbAll != null) {
            cbAll.setChecked(checked);
        }
        int count = adapter.getCount();
        for (int i = 0; i < count; i++) {
            list.get(i).put("checked", checked ? "1" : "0");
        }
        adapter.notifyDataSetChanged();
        refreshCount();
    }


    private void initModuleEvent() {
        if (ivClose != null) {
            final Animation operatingAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.open);
            operatingAnim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    int left = ivClose.getLeft();
                    int top = ivClose.getTop();
                    int width = ivClose.getWidth();
                    int height = ivClose.getHeight();
                    ivClose.clearAnimation();
                    ivClose.layout(left, top, left + width, top + height);
                }
            });
            ivClose.startAnimation(operatingAnim);
            ivClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (llClose.getVisibility() == View.VISIBLE) {
                        llClose.setVisibility(View.GONE);
                        ivClose.setImageResource(R.drawable.close);
                    } else {
                        llClose.setVisibility(View.VISIBLE);
                        ivClose.setImageResource(R.drawable.open);
                    }
                }
            });
        }
        if (cbAll != null && adapter.enableManualSelection) {
            cbAll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    changeAll(cbAll.isChecked());
                }
            });
        }
        if (tvNowDate != null) {
            tvNowDate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Calendar cal = DateUtils.convertToCalendar(tvNowDate.getText().toString(), DateUtils.DATE_FORMAT);
                    new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            int month = (monthOfYear + 1);
                            tvNowDate.setText(year + "-" + (month > 9 ? month : "0" + month) + "-" + (dayOfMonth > 9 ? dayOfMonth : "0" + dayOfMonth));
                        }
                    }, cal.get(Calendar.YEAR), ///< 设置默认启动显示年、月、日，可以自行修改为其他情况！
                            cal.get(Calendar.MONTH),
                            cal.get(Calendar.DAY_OF_MONTH)).show();
                }
            });
        }
        initLoadFocusView();
    }

    private void initLoadFocusView() {
        if (getLoadFocusView() != null) {
            getLoadFocusView().requestFocus();
        } else {
            /*if (findViewById(R.id.tv_wmsTools) != null) {
                findViewById(R.id.tv_wmsTools).requestFocus();
            } else*/
            if (tvCode != null) {
                tvCode.requestFocus();
            }
        }
    }

    protected void intModuleData() {
        if (tvNowDate != null) {
            service.getNowDate(new JsonSuccessListener() {
                @Override
                public void onRespone(String msg, JSONObject response) {
                    tvNowDate.setText(response.optString("data"));
                }
            });
        }
    }

    protected int getNowDateResId() {
        return -1;
    }

    /**
     * 启动扫码，
     */
    protected void onScan() {
        if (AppUtil.checkAndRequestPermissions(getActivity(), AppUtil.SCAN_PERMISSIONS, AppUtil.REQUEST_CODE_PERMISSION_SCAN)) {
            Intent sweep = new Intent(getActivity(), CaptureActivity.class);
            startActivityForResult(sweep, AppUtil.REQUEST_CODE_PERMISSION_SCAN);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == AppUtil.REQUEST_CODE_PERMISSION_SCAN) {
            if (!AppUtil.checkPermissionsByCode(grantResults)) {
                ToastUtils.makeText(this, "你禁用了相应的权限申请，将不可以扫码。", ToastUtils.LENGTH_SHORT).show();
            } else {
                onScan();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppUtil.REQUEST_CODE_PERMISSION_SCAN) {
            if (resultCode == RESULT_OK) {
                if (data.getExtras() != null) {
                    String result = data.getExtras().getString("result");
                    onScanResult(result);
                }
            }
        }
    }

    protected void onScanResult(String result) {

    }

    /**
     * 获取首期圆形时的第一个焦点位置
     *
     * @return
     */
    protected View getLoadFocusView() {
        return null;
    }

    protected JSONObject getObject() {
        JSONObject object = null;
        try {
            object = new JSONObject(getIntent().getStringExtra("object"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object;
    }

    private void initActionBar() {
        ActionBar actionBar = this.getSupportActionBar();
        assert actionBar != null;
        actionBar.setTitle(getObject().optString("name"));
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    protected void setFocuse(final View view) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                view.requestFocus();
            }
        }, 100);
    }

    public interface OnEnterEventListener {
        /**
         * 回车事件
         *
         * @param et
         * @return 返回true表示不执行该值事件，返回false表示继续执行该值事件，
         */
        boolean onEnter(EditText et);
    }

    /**
     * 确认用户验证回调，
     */
    public interface OnEnterUserListener {
        void onEnter(JSONObject userInfo, OnEnterUserCallBack callBack);
    }

    public interface OnEnterUserCallBack {
        void onSuccess();

        void onFail(String msg);
    }
}
